package com.yu.waterstation.app.moudles.ticketorder.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yu.waterstation.app.moudles.student.service.StudentServiceImpl;
import com.yu.waterstation.app.moudles.ticketgoods.mapper.TicketGoodsMapper;
import com.yu.waterstation.app.moudles.ticketorder.mapper.TicketOrderMapper;
import com.yu.waterstation.common.common.enums.OrderStatus;
import com.yu.waterstation.common.common.exception.ServiceException;
import com.yu.waterstation.common.entity.app.TicketGoods;
import com.yu.waterstation.common.entity.app.TicketOrder;
import com.yu.waterstation.common.entity.app.dto.StudentDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class TicketOrderService {

    @Resource
    private TicketOrderMapper ticketOrderMapper;
    @Resource
    private TicketGoodsMapper ticketGoodsMapper;
    @Resource
    private StudentServiceImpl studentService;

    // 寝室的历史订单
    public List<TicketOrder> getOrderHistoryByAddressId(Integer addressId) {
        return ticketOrderMapper.selectList(new QueryWrapper<TicketOrder>().eq("address_id", addressId));
    }

    /**
     * 创建订单
     *
     * @param ticketGoodsId 商品id
     * @param studentId     学生id
     * @param payType       支付方式
     * @return 订单id
     * @throws ServiceException 寝室不存在
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer createOrder(Integer ticketGoodsId, String payType, Integer studentId) throws ServiceException {
        StudentDTO studentInfo = studentService.getStudentInfo(studentId);
        TicketGoods goods = ticketGoodsMapper.selectById(ticketGoodsId);
        TicketOrder order = new TicketOrder();
        order.setGoodsTitle(goods.getGoodsTitle());
        order.setOrderCreator(studentInfo.getName());
        order.setOrderPrice(goods.getGoodsPrice());
        if (studentInfo.getAddress() == null)
            throw ServiceException.CONST_has_not_set_address;
        order.setAddress(studentInfo.getAddress().getDorm() + studentInfo.getAddress().getRoom());
        order.setPayType(payType);
        order.setOrderStatus(OrderStatus.ENUM_not_pay.code);
        order.setCreateTime(new Date());
        ticketOrderMapper.insert(order);
        return order.getId();
    }


    // 取消寝室的水票订单
    @Transactional(rollbackFor = Exception.class)
    public int cancelOrder(Integer orderId, Integer studentId) {
        Integer addressId = studentService.getStudentInfo(studentId).getAddress().getId();
        return ticketOrderMapper.cancelOrder(orderId, addressId, OrderStatus.ENUM_has_canceled, OrderStatus.ENUM_has_finished);
    }
}
